<?php

namespace app\models\search;

use app\models\CtiCdr;
use yii\base\Model;
use yii\data\ActiveDataProvider;

class CtiCdrSearch extends CtiCdr
{
    public function rules()
    {
        return [
            [['id', 'start_epoch', 'answer_epoch', 'end_epoch', 'duration', 'billsec'], 'integer'],
            [['direction','user_name', 'sip_from_user','telephone_assignment', 'sip_to_user','user_context', 'continue_on_fail', 'call_uuid', 'bridge_uuid', 'remark'], 'safe'],
        ];
    }

    public function scenarios()
    {
        return Model::scenarios();
    }

    /**
     * @param array $传递的参数，数组
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = CtiCdr::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        //设置前端传来的需要查询的数据
        $this->load($params,"");
//        :"",//通话时长
//        continue_on_fail:"",//结束原因
//        phone:"",//电话
//        direction:"",//拨入/拨出
//        telephone_assignment:"",//号码归属地
//        timeZone:"",//时间区间
        if (!$this->validate()) {
            return $dataProvider;
        }
        $query->andFilterWhere([
//            'id' => $this->id,
//            'start_epoch' => $this->start_epoch,
//            'answer_epoch' => $this->answer_epoch,
//            'end_epoch' => $this->end_epoch,
//            'duration' => $this->duration,
//            'billsec' => $this->billsec,
        ]);
        if (count($params['search']['timeZone'])>1){//对时间区间进行处理，转化为时间戳
            $query->andFilterWhere(['between', 'start_epoch', $params['search']['timeZone'][0]/1000,$params['search']['timeZone'][1]/1000]);//拨打时间区间
        }
        $query
            //将没必要的注释掉提高速度，
            ->andFilterWhere(['>', 'billsec', $params['search']['billsec']])//通话时长
            ->andFilterWhere(['like', 'continue_on_fail', $params['search']['continue_on_fail']])//结束原因
            ->andFilterWhere(['like', 'direction', $params['search']['direction']])//拨入/拨出
            ->andFilterWhere(['like', 'telephone_assignment', $params['search']['telephone_assignment']])//号码归属地
            ->andFilterWhere(['like', 'user_name', $this->user_name])
            ->andFilterWhere(['like', 'sip_from_user', $params['search']['sip_from_user']])//播出电话
            ->andFilterWhere(['like', 'sip_to_user', $params['search']['sip_to_user']]);//接听电话

        if ($params['search']['answered']==1){
            $query
                ->andFilterWhere(['>', 'answer_epoch',0]);//电话已经接通1
        }
        if ($params['search']['answered']==2){
            $query
                ->andFilterWhere(['=', 'answer_epoch',0]);//电话未接通2
        }

        return $dataProvider;
    }
}
